﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="价格表名称" prop="ListName">
            <a-input v-model="entity.ListName" autocomplete="off" placeholder="价格表名称" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="客户" prop="CusCode">
            <a-row>
              <a-col :span="20">
                <a-input :value="entity.CusCode?(entity.CusCode+'/'+entity.CustomerName):''" disabled></a-input>
              </a-col>
              <a-col :span="4"><a-button icon="search" type="primary" style="width: 100%;margin-top: 4px;" @click="openClient"></a-button></a-col>
            </a-row>

          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-textarea v-model="entity.Remark" autocomplete="off" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-table
      class="tables"
      ref="table"
      :scroll="{ y: 460 }"
      :columns="columns"
      :rowKey="(row, index) => row.cInvCode"
      :dataSource="data"
      :pagination="pagination"
      @change="handleTableChange"
      :bordered="true"
      size="small"
    >
      <template slot="cInvName" slot-scope="text, record">
        <span>{{ record.cInvCode }}/{{ record.cInvName }}</span>
      </template>

      <span slot="action" slot-scope="text, record, index">
        <template>
          <a v-if="hasPerm('SO_CustomerPriceListItem.Delete')" @click="handleDelete(index, [record.Id], [record])">删除</a>
        </template>
      </span>

      <template slot="BasePrice" slot-scope="text, record">
        <a-input-number
          style="text-align: right;width: 100%"
          class="input"
          :step="0.01"
          v-model="record.BasePrice"
        ></a-input-number>
      </template>
      <template slot="iTaxUnitPrice" slot-scope="text, record">
        <a-input-number
          style="text-align: right;width: 100%"
          class="input"
          :step="0.01"
          v-model="record.iTaxUnitPrice"
        ></a-input-number>
      </template>
      <template slot="aid" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime,'YYYY-MM-DD HH:mm') }}</span>
      <span slot="UpdateTime" slot-scope="UpdateTime">{{ timeFormat(UpdateTime,'YYYY-MM-DD HH:mm') }}</span>
    </a-table>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <clientChoose ref="clientChoose" @onChoose="cCusCodeChange"></clientChoose>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp; <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import MaterialChoose from '../SO_SOMain/materialChoose.vue'
import clientChoose from '../SO_SOMain/clientChoose'
import moment from 'moment'
const columns = [
  {
    title: '序号',
    dataIndex: 'aid',
    align: 'center',
    scopedSlots: { customRender: 'aid' },
    width: '50px'
  },
  { title: '编号', dataIndex: 'cInvCode', width: '10%' },
  { title: '品名', dataIndex: 'cInvName', width: '10%' },
  { title: '规格型号', dataIndex: 'cInvStd', width: '10%' },
  {
    title: '底价',
    dataIndex: 'BasePrice',
    align: 'right',
    scopedSlots: { customRender: 'BasePrice' }
  },

  {
    title: '销售价格',
    dataIndex: 'iTaxUnitPrice',
    align: 'right',
    scopedSlots: { customRender: 'iTaxUnitPrice' }
  },
  { title: '添加日期', dataIndex: 'CreateTime', scopedSlots: { customRender: 'CreateTime' }, align: 'center', width: '10%' },
  { title: '更新日期', dataIndex: 'UpdateTime', scopedSlots: { customRender: 'UpdateTime' }, align: 'center', width: '10%' },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]

export default {
  props: {
    parentObj: Object
  },
  components: {
    MaterialChoose, clientChoose
  },
  watch: {
    data: {
      handler (n, o) {
        // console.log(n)
        n.forEach(item => {
          if (Number(item.StandardPrice) < 0) {
            this.$set(item, 'StandardPrice', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.MinimumDiscount) < 0) {
            this.$set(item, 'MinimumDiscount', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.MinimumDiscount) > 100) {
            this.$set(item, 'MinimumDiscount', 100)
            this.$message.warning('不能大于100')
            return
          }
          if (Number(item.NumLowerLimit1) < 0) {
            this.$set(item, 'NumLowerLimit1', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.LowerLimitPrice1) < 0) {
            this.$set(item, 'LowerLimitPrice1', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.NumLowerLimit2) < 0) {
            this.$set(item, 'NumLowerLimit2', 1)
            this.$message.warning('不能小于0')
            return
          }

          if (Number(item.LowerLimitPrice2) < 0) {
            this.$set(item, 'LowerLimitPrice2', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.NumLowerLimit3) < 0) {
            this.$set(item, 'NumLowerLimit3', 1)
            this.$message.warning('不能小于0')
            return
          }
          if (Number(item.LowerLimitPrice3) < 0) {
            this.$set(item, 'LowerLimitPrice3', 1)
            this.$message.warning('不能小于0')
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      columns,
      Id: '',
      QPLD_List: [],
      queryParam: {},
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },

      selectedRowKeys: [],
      data: [],
      visible: false,

      entity: {},
      rules: {
        ListName: [{ required: true, message: '未输入', trigger: 'blur' }],
        CusCode: [{ required: true, message: '未选择', trigger: 'blur' }]
      },
      title: ''
    }
  },
  methods: {
    disabledDate (current) {
      const startValue = this.entity.StartValidity
      if (startValue) {
        return startValue.valueOf() >= current.valueOf()
      } else {
        return current.valueOf() <= moment().subtract(1, 'days')
      }
    },
    openClient () {
      this.$refs.clientChoose.openChoose(this.entity.CompanyId)
    },
    // 客户选择
    cCusCodeChange (arr) {
      console.log(arr)
      const obj = arr[0]
      if (obj) {
        this.$set(this.entity, 'CusCode', obj.cCusCode)
        this.$set(this.entity, 'CustomerName', obj.cCusName)
        this.$set(this.entity, 'CustomerId', obj.Id)
        this.$refs.form.validateField('CusCode')
      }
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      if (this.Id) {
        this.$http
          .post('/OrderManagement/SO_CustomerPriceList/GetTheDataOfAll', {
            PageIndex: this.pagination.current,
            PageRows: this.pagination.pageSize,
            SortField: 'Id',
            SortType: 'desc',
            Search: {
              Condition: 'Id',
              Keyword: this.Id
            }
          })
          .then(res => {
            // console.log(res)
            if (res.Success) {
              if (res.Data.Total) {
                const pagination = { ...this.pagination }
                pagination.total = res.Data.Total
                this.pagination = pagination
              }
            } else {
              this.$message.error(res.Msg)
            }
          })
      }
    },
    addTable () {
      if (!this.entity.CusCode) {
        alert('请先选择客户！')
        return
      }
      this.$refs.materialChoose.openChoose(null, this.data)
    },

    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    close () {
      this.visible = false
      this.data = []
    },
    handleChoose (a) {
      var ar = []
      console.log(a)
      this.data.forEach(item => {
        // console.log(this.data)
        a.forEach((val, i) => {
          // console.log(val)
          if (item.InvId === val.Id) {
            ar.push(val)
            delete a[i]
          }
        })
      })
      if (ar.length === 0) {
        a.forEach(item => {
          this.data.push({
            cInvCode: item.Code,
            cInvName: item.Name,
            cInvStd: item.Spec,
            InvId: item.Id,
            BasePrice: null,
            iTaxUnitPrice: null
          })
        })
        // console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          this.data = [...this.data, item]
        })
      }
    },
    init () {
      this.data = []
      this.entity = {}
      this.$set(this.entity, 'IsLadderPrice', false)
    },
    getDataList () {
      if (this.Id) {
        this.loading = true
        this.$http.post('/OrderManagement/SO_CustomerPriceList/GetTheData', { id: this.Id }).then(resJson => {
          this.loading = false
          this.entity = resJson.Data || {}
          this.data = resJson.Data.Items || []
        })
      }
    },

    // 子表删除
    handleDelete (index, ids, rows) {
      let deleteIdArr = []
      // 给每一行设置选中值用于后续判断逻辑
      rows.forEach((item) => (item['checked'] = true))
      // this.data.forEach((item) => (item['checked'] = true))
      // 过滤有id的列表用于提交请求id数组
      const newdata = rows.filter((item) => item.Id)
      if (newdata.length > 0) {
        // 说明有id
        deleteIdArr = newdata.map((item) => {
          return item.Id
        })
      }
      console.log(newdata)
      if (this.title === '编辑客户价格表信息') {
        // 判断如果是当前行删除  直接删除
        if (ids === undefined) return this.data.splice(index, 1)
        // 判断要删除的数组中是否存在返回的id列表 再弹窗 否则直接删除即可
        const isBool = rows.some((item) => item.Id)
        console.log(isBool)
        if (isBool) {
          this.$confirm('确认删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return new Promise((resolve, reject) => {
              this.$http.post('/OrderManagement/SO_CustomerPriceListItem/DeleteData', deleteIdArr).then((res) => {
                if (res.Success) {
                  this.loading = false
                  // 对比处理id  过滤出没有符合条件的重新赋值子表
                  this.data.forEach(item => {
                    deleteIdArr.forEach(v => {
                      if (item.Id === v) {
                        item.checked = true
                      }
                    })
                  })
                  // 过滤出没有选中删除的数组重新赋值 为已删除列表
                  const resultArr = this.data.filter((item) => !item.checked)
                  this.data = resultArr
                  // 删除选中列表初始化
                  this.selectedRowKeys = []
                  this.$message.success('删除成功')
                } else {
                  this.loading = false
                  // 删除选中列表初始化
                  this.selectedRowKeys = []
                  this.$message.error(res.Msg)
                }
              })
            }).catch(() => console.log('Oops errors!'))
          })
        } else {
          const resultArr = this.data.filter((item) => !item.checked)
          this.data = resultArr
          // 删除选中列表初始化
          this.selectedRowKeys = []
        }
      } else {
        // 给每一行设置选中值用于后续判断逻辑
        this.data.forEach((item) => (item['checked'] = true))
        // 过滤出没有选中删除的数组重新赋值 为已删除列表
        const resultArr = this.data.filter(item => item.Id !== rows[0].Id)
        this.data = resultArr
        // 删除选中列表初始化
        this.selectedRowKeys = []
      }
    },
    // handleDelete (ids, index) {
    //   if (ids[0]) {
    //     var thisObj = this
    //     this.$confirm({
    //       title: '确认删除吗?',
    //       onOk () {
    //         return new Promise((resolve, reject) => {
    //           thisObj.$http.post('/OrderManagement/SO_CustomerPriceListItem/DeleteData', ids).then(resJson => {
    //             resolve()
    //
    //             if (resJson.Success) {
    //               thisObj.$message.success('操作成功!')
    //
    //               thisObj.getDataList()
    //             } else {
    //               thisObj.$message.error(resJson.Msg)
    //             }
    //           })
    //         })
    //       }
    //     })
    //   } else {
    //     this.data.splice(index, 1)
    //   }
    // },
    openForm (id, title) {
      this.init()

      this.title = title
      if (id) {
        this.Id = id
        this.getDataList()
      }
      this.visible = true
    },
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        console.log(this.data)
        this.loading = true
        const BasePricecount = this.data.some(item => {
          return item.BasePrice <= 0
        })
        console.log(BasePricecount)
        if (BasePricecount) {
          this.$message.error('底价不能为空')
          return
        }
        const iTaxUnitPricecount = this.data.some(item => {
          return item.iTaxUnitPrice <= 0
        })
        console.log(iTaxUnitPricecount)
        if (iTaxUnitPricecount) {
          this.$message.error('销售价格不能为空')
          return
        }
        var entityData = { ...this.entity }
        this.Items = [...this.data]
        entityData.Items = this.Items
        this.$http.post('/OrderManagement/SO_CustomerPriceList/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false

            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    },
    timeFormat (val, format) {
      // 时间格式化函数
      return moment(val).format(format)
    }
  }
}
</script>
